import { useMemo, useRef, useState } from 'react';
import { StyleSheet } from 'react-native';
import { Video, VideoRef } from 'react-native-video';

import { SoundPlayerContext, SoundPlayerType } from './content';

const SoundPlayer: React.FC<React.PropsWithChildren> = ({ children }) => {
  const [playing, setPlaying] = useState(false);
  const soundRef = useRef<VideoRef>(null);
  // 播放速度
  const [rate, setRate] = useState(1);
  /** 设置播放 */
  const handleSetSoundUri = (uri: string) => {
    soundRef.current?.setSource({ uri });
  };
  /** 暂停播放 */
  const handlePauseSound = () => {
    soundRef.current?.pause();
    setPlaying(false);
  };
  /** 停止播放 */
  const handleStopSound = () => {
    soundRef.current?.pause();
    soundRef.current?.seek(0);
    setPlaying(false);
  };
  /** 从头播放 */
  const handlePlaySound = () => {
    soundRef.current?.seek(0);
    soundRef.current?.resume();
    setPlaying(true);
  };
  /** 继续播放 */
  const handleContinueSound = () => {
    soundRef.current?.resume();
    setPlaying(true);
  };

  const handleSpeedChange = (value: number) => {
    setRate(value);
  };

  const value: SoundPlayerType = useMemo(() => {
    return {
      setSoundUri: handleSetSoundUri,
      onPause: handlePauseSound,
      onStop: handleStopSound,
      onPlay: handlePlaySound,
      onReplay: handleContinueSound,
      playing: playing,
      onSpeedChange: handleSpeedChange,
    };
  }, [playing]);

  return (
    <SoundPlayerContext.Provider value={value}>
      <Video
        ref={soundRef}
        style={styles.sound}
        pointerEvents="none"
        focusable={false}
        paused={false} // 设置播放状态
        repeat={false} // 设置重复播放
        rate={rate}
        onEnd={handleStopSound}
      />
      {children}
    </SoundPlayerContext.Provider>
  );
};

const styles = StyleSheet.create({
  sound: {
    opacity: 0,
  },
});

export default SoundPlayer;
